import {
    getEmployeeInfoByRole,
    getAllEmployeeInfo,
    deleteEmployee,
    getEmployeeInfoByName,
    getEmployeeInfoByEmployeeNo,
} from "@/api/employeeApi";

export default {
    data() {
        return {
            seach: {
                state: "",
                name: "",
                employeeNo: ""
            },
            allData: [],      // 存储所有数据
            pages: [],        // 当前页显示的数据
            currentPage: 1,   // 当前页码
            pageSize: 6,     // 每页显示条数
            total: 0         // 总数据量
        };
    },
    created() {
        this.seach.state = 100;
        this.loaddate();
    },
    methods: {
        // 更新当前页数据
        updateTableData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.pages = this.allData.slice(start, end);
            this.total = this.allData.length;
        },

        async loaddate() {
            let role = Number(this.seach.state);
            if (!isNaN(role)) {
                if(role === 100){
                    await this.getAllEmployeeInfo();
                } else {
                    await this.getEmployeeInfoByRole(role);
                }
            }
            this.updateTableData();
        },

        async getAllEmployeeInfo() {
            try {
                const result = await getAllEmployeeInfo();
                if (result.code === 200) {
                    this.allData = result.data;
                } else {
                    this.$message.error('查询失败');
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        async getEmployeeInfoByRole(role) {
            try {
                const result = await getEmployeeInfoByRole(role);
                if (result.code === 200) {
                    this.allData = result.data;
                } else {
                    this.$message.error('查询失败');
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        async loadDataByName() {
            try {
                const empResult = await getEmployeeInfoByName(this.seach.name);
                if (empResult.code === 200) {
                    this.allData = empResult.data;
                    this.updateTableData();
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        async loadDataByEmployeeNo() {
            try {
                const empResult = await getEmployeeInfoByEmployeeNo(this.seach.employeeNo);
                if (empResult.code === 200) {
                    // 单个员工也转为数组形式
                    this.allData = empResult.data ? [empResult.data] : [];
                    this.updateTableData();
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },

        // 分页处理
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1;
            this.updateTableData();
        },

        handleCurrentChange(val) {
            this.currentPage = val;
            this.updateTableData();
        },

        // 导出员工名单为CSV
        exportEmployeeList() {
            if (!this.allData || this.allData.length === 0) {
                this.$message.warning('没有可导出的数据');
                return;
            }

            try {
                // 1. 准备CSV内容（添加BOM头解决中文乱码）
                let csvContent = "\uFEFF";

                // 2. 添加表头（中文）
                csvContent += "员工ID,工号,姓名,电话,邮箱,部门,职位,入职日期\n";

                // 3. 添加数据行
                this.allData.forEach(employee => {
                    csvContent += [
                        employee.employeeId,
                        `"${employee.employeeNo}"`,
                        `"${employee.employeeName}"`,
                        `"${employee.employeePhone || ''}"`,
                        `"${employee.email || ''}"`,
                        employee.departmentId,
                        `"${employee.position || ''}"`,
                        `"${employee.hireDate || ''}"`
                    ].join(',') + '\n';
                });

                // 4. 创建Blob对象
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

                // 5. 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.href = url;

                // 6. 设置文件名（使用当前日期）
                const now = new Date();
                const dateStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
                link.setAttribute('download', `员工名单_${dateStr}.csv`);

                // 7. 触发下载
                document.body.appendChild(link);
                link.click();

                // 8. 清理
                setTimeout(() => {
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                }, 100);

            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败: ' + error.message);
            }
        },

        goToEmployeeInfo(employeeId) {
            this.$router.push({ path: `/employee/EmployeeInfo/${employeeId}`});
        },

        async deleteEmployee(employeeId) {
            try {
                await this.$confirm('确定要删除该员工吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const result = await deleteEmployee(employeeId);
                if (result.code === 200) {
                    this.$message.success('删除成功');
                    // 重新加载数据
                    await this.loaddate();
                    // 如果删除的是当前页最后一条数据且不是第一页，则返回上一页
                    if (this.pages.length === 0 && this.currentPage > 1) {
                        this.currentPage--;
                        this.updateTableData();
                    }
                } else {
                    this.$message.error('删除失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error);
                    this.$alert('网络错误，请稍后再试', '提示', {
                        confirmButtonText: '确定'
                    });
                }
            }
        },

        NewEmployee() {
            this.$router.replace({ path: '/employee/AddEmployee' });
        }
    }
};